package logic

import (
	"context"
	"fmt"
	"shopping-mall/models/mysql"
	"shopping-mall/models/redis"

	"shopping-mall/shoppingrpc/internal/svc"
	"shopping-mall/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductsLikeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductsLikeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductsLikeLogic {
	return &ProductsLikeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductsLikeLogic) ProductsLike(in *shoppingrpc.ProductsLikeRequest) (*shoppingrpc.ProductsLikeResponse, error) {
	// todo: add your logic here and delete this line

	var product mysql.Product
	err := mysql.Db.Debug().Where("id = ?", in.ProductId).Find(&product).Error
	if err != nil {
		return nil, err
	}
	if product.ID == 0 {
		return nil, fmt.Errorf("当前商品不存在")
	}

	// 更新 Redis 中的点赞数
	redis.Rdb.ZIncrBy("productLike", 1, product.Name)
	//更新数据库的点赞数

	return &shoppingrpc.ProductsLikeResponse{Id: int64(product.ID)}, nil
}
